package com.example.summer_pro.controller;

import com.example.summer_pro.common.Respond;
import com.example.summer_pro.common.NormalData;
import com.example.summer_pro.entity.Normal;
import com.example.summer_pro.entity.NormalsJSON;
import com.example.summer_pro.entity.Ques;
import com.example.summer_pro.service.NormalService;
import com.example.summer_pro.service.QuesService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@CrossOrigin
public class NormalController {
    @Autowired
    private NormalService normalService;
    @Autowired
    private QuesService quesService;
    //1.添加题目
    @PostMapping("/addNormal")
    public Map<String, Object> addNormal(@RequestBody Map<String, List<String>> remap) {
        System.out.println("use normalController");
        String type = LtoS(remap.get("t_type"));
        String necessity_s = LtoS(remap.get("necessity"));
        Integer q_id = LtoI(remap.get("q_id"));
        Integer t_id = LtoI(remap.get("t_id"));
        Integer t_num = LtoI(remap.get("t_num"));
        String content = LtoS(remap.get("content"));
        Boolean necessity = false;
        if(necessity_s.equals("true")) {
            necessity = true;
        }

        //Normal normal=new Normal(q_id, t_id,t_num,type,,,content,necessity);
        Map<String, Object> map = new HashMap<>();
        try {
            //normalService.addNewNormal(normal);
            map.put("success",true);
            map.put("message","添加成功");

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "添加失败！");
        }
        return map;
    }
    //2.复制题目

    //3.删除题目
    @PostMapping("/deteleNormal")
    public Map<String, Object> deleteNormal(@RequestBody Map<String, String> remap) {
        Integer q_id=Integer.parseInt(remap.get(""));
        Integer t_id=Integer.parseInt(remap.get(""));
        Map<String, Object> map = new HashMap<>();
        try {
            Normal normal=normalService.selectNormal(q_id,t_id);
            normalService.updateNormal(normal);
            map.put("success", true);
            map.put("message","删除成功");

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "操作失败！");
        }
        return map;
    }
    //4.调整题目顺序

    //5.显示题号/取消显示题号

    //6.编辑题目;可以添加描述的必要信息，设置是否必填;在编辑过程中，即时保存
    @PostMapping("/updateNormal")
    public Map<String, Object> updateNormal(@RequestBody Map<String, String> remap) {
        String type=remap.get("");
        Boolean necessity=Boolean.getBoolean(remap.get(""));
        Integer q_id=Integer.parseInt(remap.get(""));
        Integer t_id=Integer.parseInt(remap.get(""));
        Integer t_num=Integer.parseInt(remap.get(""));
        String content=remap.get("");
        Map<String, Object> map = new HashMap<>();
        try {
            //Normal normal = new Normal(q_id,t_id,t_num,type,content,necessity);
            //normalService.updateNormal(normal);
            map.put("success", true);
            map.put("message","修改成功");

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "操作失败！");
        }
        return map;
    }
    //7.发布问卷;发布形式：链接和二维码（需要考虑泄露时如何处理）

    //8.保存问卷；用户可以随时保存

    public String LtoS(List<String> list){
        String s="";
        for(int i=0;i<list.size();i++){
            if(i==0){
                s=list.get(0);
            }
            else {
                s=s+"_"+list.get(i);
            }
        }
        return s;
    }
    public Integer LtoI(List<String> list){
        String Int=LtoS(list);
        Integer i = Integer.parseInt(Int);
        return i;
    }
  /*  @PostMapping("/test")
    public Map<String, Object> testNormal(@RequestBody Map<String, Object> remap) {
        Object obj=remap.get("questions");
        System.out.println(obj);
        System.out.println("----------------");
        //String.valueOf(object)
        System.out.println(String.valueOf(obj));
        System.out.println("----------------");
        Map<String, Object> map = new HashMap<>();
        map.put("success",true);
        return map;
    }*/
  @PostMapping("/test")
  public Respond testPage(
          @RequestBody NormalData normalData
  ){
      System.out.println(normalService.selectJson(normalData.getQ_id()));
      String strJson=JSON.toJSONString(normalData);
      System.out.println(strJson);
      //System.out.println(testData.getQuestions().get(1));
      System.out.println("--------------");
      System.out.println(normalData.getQuestions());
      System.out.println("--------------");
      System.out.println(normalData.getQuestions().get(0).getType());
     // System.out.println(testData.getQuestions().get(0).getOptions());

      int ops= normalData.getQuestions().get(0).getOptions().size();
      ArrayList<String> list=new ArrayList<>();
      for(int j=0;j<ops;j++)
      {
         // System.out.println(testData.getQuestions().get(0).getOptions().get(j).getText());
            list.add(normalData.getQuestions().get(0).getOptions().get(j).getText());
      }
      System.out.println(list);
      String str =list.toString();
      System.out.println(str);
      //String str2= = Joiner.on("***").join(list);


      System.out.println("--------------");
      System.out.println(normalData.getQuestions().get(1));
      System.out.println("--------------");
      System.out.println(normalData.getQuestions().get(1).getOptions().size());
      return new Respond(true, "OK", "");
  }
    @PostMapping("/questions")
    public Respond addAllQuestions(
            @RequestBody NormalData normalData
    ){
      //q_id前端要传，目前暂时定义为0
        Integer q_id=5;
        q_id= normalData.getQ_id();
        Ques ques = quesService.getQuesByQid(q_id);
        if(ques!=null){
            normalData.setTitle(ques.getTitle());
            normalData.setQ_type(ques.getQ_type());
        }
        String strJson = JSON.toJSONString(normalData);
        System.out.println(strJson);
        normalService.deleteJson(q_id);
        normalService.addJson(q_id,strJson);

        normalService.deleteAllNormal(q_id);
        Integer t_id;
        Integer t_num;
        String t_type;
        String q_type = normalData.getQ_type();
        String content;
        String grades="";
        boolean necessity;
        int ops;
        t_num= normalData.getQuestions().size();
        for(int i = 0; i< normalData.getQuestions().size(); i++)
        {
            t_id=i;
            t_type= normalData.getQuestions().get(i).getType();
            //处理第i个问题的第j个选项
            ArrayList<String> list=new ArrayList<>();
            ops= normalData.getQuestions().get(i).getOptions().size();
            for(int j=0;j<ops;j++) {
                list.add(normalData.getQuestions().get(i).getOptions().get(j).getText());
                if(normalData.getQuestions().get(i).getOptions().get(j).getGrade()!=0){
                    grades = grades + normalData.getQuestions().get(i).getOptions().get(j).getGrade() + "-";
                }
            }
            content=list.toString();
            necessity= normalData.getQuestions().get(i).getRequired();
            Normal normal=new Normal(q_id,t_id,q_type,t_num,ops,grades,t_type,content,necessity);
            normalService.addNewNormal(normal);
        }

        return new Respond(true, "OK", normalData);
    }

    @PostMapping("/edit")
    public Map<String, Object> editNormals(@RequestBody Map<String, Integer> remap,HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer u_id= (Integer) session.getAttribute("u_id");
        System.out.println("u_id:"+u_id);
      Integer q_id=remap.get("q_id");
      System.out.println(q_id);
        System.out.println("edit works");

      NormalsJSON normalsJSON=normalService.selectJson(q_id);
        Map<String, Object> map = new HashMap<>();
      if(normalsJSON==null)
      {
          NormalData normalData =new NormalData();
          Ques ques = quesService.getQuesByQid(q_id);
          if(ques!=null)
              normalData.setTitle(ques.getTitle());
          else
              normalData.setTitle("null");
          normalData.setQ_id(q_id);
          normalData.setQuestions(new ArrayList<NormalData.Questions>());
          map.put("data",JSON.toJSONString(normalData));
      }
      else
      {
          map.put("data",normalsJSON.getJson());
      }
        map.put("success",true);
        return map;
    }
    @PostMapping("/copyQues")
    public Map<String, Object> copyQ(@RequestBody Map<String, Integer> remap){
      Integer idPast=remap.get("idPast");
      Integer idNow=remap.get("idNow");
      NormalsJSON normalsJSON=normalService.selectJson(idPast);
      String jsonNow=normalsJSON.getJson();
      normalService.addJson(idNow,jsonNow);
      Map<String,Object> map=new HashMap<>();
      map.put("success",true);
      return map;
    }

}


